iT邦幫忙

2021 iThome 鐵人賽

DAY 24
0

Shimmer

iOS Swift的話是類似SkeletonView
一般用在等待的時候 像是API fetch data
這邊用前幾篇的News API, 把轉圈圈修改成Shimmer

先是建立Shimmer widget class
再來是建立擺在ListView裡面的 Shimmer cell (ListViewShimmer)
這樣就可以直接替換成ListView效果

class ShimmerWidget extends StatelessWidget {
  final double width;
  final double height;
  late ShapeBorder shapeBorder;
  final double borderRadius;

  ShimmerWidget.rectangle({
    this.width = double.infinity,
    required this.height,
    this.borderRadius = 8,
  });

  @override
  Widget build(BuildContext context) {
    shapeBorder = RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(borderRadius));
    return Shimmer.fromColors(
      child: Container(
        width: width,
        height: height,
        decoration: ShapeDecoration(
          color: Colors.grey[400]!,
          shape: shapeBorder,
        ),
      ),
      baseColor: Colors.grey[400]!,
      highlightColor: Colors.grey[200]!,
    );
  }
}

class ListViewShimmer extends StatelessWidget {
  ListViewShimmer({Key? key, this.cellCount = 3}) : super(key: key);

  final int cellCount;
  final cellWidth = Get.width * 0.95;

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.start,
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: [
        ListView.builder(
          physics: BouncingScrollPhysics(),
          shrinkWrap: true,
          itemCount: cellCount,
          itemBuilder: (BuildContext context, int index) {
            return Card(
              child: ListTile(
                title: ShimmerWidget.rectangle(height: 15),
                subtitle: ShimmerWidget.rectangle(height: 10),
              ),
            );
          },
        ),
      ],
    );
  }
}

本篇的GitHub source code

下一篇將為大家介紹Shimmer和 API fetch之間的切換
AnimatedSwitcher with API fetch


上一篇
[Day23] Flutter GetX with Dio (二)
下一篇
[Day25] Flutter GetX API AnimatedSwitcher
系列文
Flutter with GetX, loading*175%歷程 30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言